
global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/montecarlo.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

capture noi {
* v1 country
* ---------------------------------------------	*
* ---------------------------------------------	*
*			Monte Carlo simulations				*
* --------------------------------------------	*
* --------------------------------------------	*

* This package takes as given the sample of firms and creates Monte Carlo
* generated estimates and standard errors, reshuffling macro-variables and correcting inference.

clear
* set seed
set seed 317 
set more off

* ---------------------------------------------	*
*				Parameters						*
* --------------------------------------------	*

* How many monte carlo runs to do? (default: 4000)
local monte_runs = 4000

* Which permutation to run?
* set to 1 to run the permutation exercise
local run_permute = $arg1
* part of run_permute; set to 1 to save the redrawn macro vars from morales and build the Borusyak and Hull (2021) mu-terms 
local run_boruhull = $arg2  
* specify the permutation version.
local pvers "$arg3"


* set to 1 to compute the bootstrap-clustered standard errors 
local run_cluster = $arg4	


* Indicate run name:
* ------------------
local run_ind = "`monte_runs'"
local rname = "`run_ind'"



* --------------------------------------------- *
*	        Run permutation                     *
* --------------------------------------------- *

* This code recreates the baseline regression results above, 
* reshuffling either country or firm weights `monte_runs' times
* and stores the associated p-values

if `run_permute' == 1 {
    * compute redrawn estimates, stores storage_runs_`pvers'_`rname'.dta
    include ${monte_dir}/run_permutation.do

    * compute p-values, stores p_values_`pvers'_`rname'.dta
    include ${monte_dir}/compute_pvalues.do
}

* --------------------------------------------- *
*			cluster_bootstrap        	    	*
* --------------------------------------------- *

* This code follows Cameron et al. (2008) and calculates significance through bootstrapping. Namely, we do so in three ways
* 1) Bootstrap and calculate the empirical standard deviation of betas. Use that as the standard deviation for a t-test on the original beta
* 2) Test each sample for deviation from the originally estimated beta. See if the original t statistic is statistically different from this sample 
* 3) 2) using clustered robust standard errors. 	

if `run_cluster' == 1  {
    * run bootstrap
    include ${monte_dir}/cluster_bootstrap.do

    * store p-values
    clear 
    set obs 1 
    gen column=.
    save ${final_dir}/p_values_cluster.dta, replace
    foreach var of numlist 1/9 {
        import delimited ${monte_data_dir}/original_estimates.csv,  clear varnames(1) case(preserve)
        gen tvalue=estimateL/standard_errorL
        sum tvalue if column==`var'
        local tvalue=`r(mean)'
        use tvar_`var'* run using ${monte_data_dir}/storage_runs_cluster.dta, clear
        sum run
        local runs = r(max) 
        gen count_it=0
        replace count_it=1 if abs(tvar_`var')>abs(`tvalue')
        sum count_it
        local p_value=`r(mean)'
        clear 
        set obs 1
        gen column=`var'
        gen p_value=`p_value'
        gen wage_type="separate wages"
        gen runs = `runs'
        append using ${final_dir}/p_values_cluster.dta
        drop if column==.
        sleep 1000
        save ${final_dir}/p_values_cluster.dta, replace
    }
}	

}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat